﻿/* 
 * Since 2008 - 2012
 */

package com.hh.bss.talent.service.impl;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.sql.Types;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.util.SubsetIteratorFilter.Decider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hh.bss.auth.client.OnlineUser;
import com.hh.bss.auth.service.SystemUserService;
import com.hh.bss.base.BaseBusinessService;
import com.hh.bss.base.EntityDao;
import com.hh.bss.common.ConstantDic;
import com.hh.bss.common.MapObjectRowMapper;
import com.hh.bss.common.SystemConstant;
import com.hh.bss.common.cache.CustomerCache;
import com.hh.bss.common.cache.SystemDicCache;
import com.hh.bss.common.page.Page;
import com.hh.bss.config.Environment;
import com.hh.bss.customer.dao.CustomerContacterDao;
import com.hh.bss.customer.entity.Company;
import com.hh.bss.customer.entity.CompanyCv;
import com.hh.bss.customer.entity.CustomerContacter;
import com.hh.bss.customer.service.CompanyService;
import com.hh.bss.mail.SendMailInfo;
import com.hh.bss.mail.SendMailUtil;
import com.hh.bss.oa.entity.OaEmailSend;
import com.hh.bss.oa.service.OaEmailSendService;
import com.hh.bss.project.entity.ContractJob;
import com.hh.bss.project.entity.SearchProjectCv;
import com.hh.bss.project.entity.SearchProjectCvCrm;
import com.hh.bss.project.service.ContractJobService;
import com.hh.bss.project.service.SearchProjectCvCrmService;
import com.hh.bss.project.service.SearchProjectCvService;
import com.hh.bss.sysadmin.entity.SystemDic;
import com.hh.bss.talent.dao.CvCertificateDao;
import com.hh.bss.talent.dao.CvContactDetailDao;
import com.hh.bss.talent.dao.CvDao;
import com.hh.bss.talent.dao.CvEducationDao;
import com.hh.bss.talent.dao.CvSalaryDao;
import com.hh.bss.talent.dao.CvTrainningDao;
import com.hh.bss.talent.dao.CvWorkDao;
import com.hh.bss.talent.entity.Cv;
import com.hh.bss.talent.entity.CvAttachment;
import com.hh.bss.talent.entity.CvCertificate;
import com.hh.bss.talent.entity.CvContactDetail;
import com.hh.bss.talent.entity.CvEducation;
import com.hh.bss.talent.entity.CvSalary;
import com.hh.bss.talent.entity.CvTrainning;
import com.hh.bss.talent.entity.CvWork;
import com.hh.bss.talent.service.CvService;
import com.hh.bss.talent.vo.query.CvCustomerContacterQuery;
import com.hh.bss.talent.vo.query.CvQuery;
import com.hh.bss.talent.vo.query.CvResume;
import com.hh.bss.talent.vo.query.CvSuccessQuery;
import com.hh.bss.util.BeanUtils;
import com.hh.bss.util.DESHelper;
import com.hh.bss.util.DateHelper;
import com.hh.bss.util.ExcelHelper;
import com.hh.bss.util.FileHelper;
import com.hh.bss.util.ObjectUtils;
import com.hh.bss.util.RandomStringUtil;
import com.hh.bss.util.StringHelper;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

@Service
@Transactional
public class CvServiceImpl extends BaseBusinessService<Cv, java.lang.Integer> implements CvService<Cv, java.lang.Integer> {

	private CvDao cvDao;

	/** 增加setXXXX()方法,spring就可以通过autowire自动设置对象属性,请注意大小写 */
	public void setCvDaoImpl(CvDao dao) {
		this.cvDao = dao;
	}

	private CvEducationDao cvEducationDao;
	private CvCertificateDao cvCertificateDao;
	private CvTrainningDao cvTrainningDao;
	private CvWorkDao cvWorkDao;
	private CvContactDetailDao contactDetailDao;
	private CvSalaryDao salaryDao;
	private CustomerContacterDao customerContacterDao;
	private CompanyService companyService;
	private ContractJobService contractJobService;
	private SystemUserService systemUserService;
	private OaEmailSendService oaEmailSendService;
	private SearchProjectCvService searchProjectCvService;

	@Autowired
	private SearchProjectCvCrmService crmService;

	public void setSystemUserService(SystemUserService systemUserService) {
		this.systemUserService = systemUserService;
	}

	public void setOaEmailSendServiceImpl(OaEmailSendService service) {
		this.oaEmailSendService = service;
	}

	public void setSearchProjectCvServiceImpl(SearchProjectCvService service) {
		this.searchProjectCvService = service;
	}

	public void setContractJobServiceImpl(ContractJobService service) {
		this.contractJobService = service;
	}

	public void setCompanyServiceImpl(CompanyService service) {
		this.companyService = service;
	}

	@Autowired
	public void setEducationDao(CvEducationDao dao) {
		this.cvEducationDao = dao;
	}

	@Autowired
	public void setCertificateDao(CvCertificateDao dao) {
		this.cvCertificateDao = dao;
	}

	@Autowired
	public void setTrainningDao(CvTrainningDao dao) {
		this.cvTrainningDao = dao;
	}

	@Autowired
	public void setWorkDao(CvWorkDao dao) {
		this.cvWorkDao = dao;
	}

	@Autowired
	public void setCvContactDetailDaoImpl(CvContactDetailDao contactDetailDao) {
		this.contactDetailDao = contactDetailDao;
	}

	public void setCustomerContacterDaoImpl(CustomerContacterDao customerContacterDao) {
		this.customerContacterDao = customerContacterDao;
	}

	@Autowired
	public void setSalaryDao(CvSalaryDao salaryDao) {
		this.salaryDao = salaryDao;
	}

	public EntityDao getEntityDao() {
		return this.cvDao;
	}

	@Transactional(readOnly = true)
	public Page findPage(CvQuery query) {
		return cvDao.findPage(query);
	}

	public Page findSimpleCvPage(CvQuery query) {
		Page page = cvDao.findSimpleCvPage(query);
		return page;
	}

	public Page findCvPage(CvQuery query) {
		Page page = cvDao.findCvPage(query);

		List<Cv> cvlist = (List) page.getResult();
		// 设置cc项目名
		Map m = null;
		for (int i = 0; cvlist != null && i < cvlist.size(); i++) {
			m = (Map) cvlist.get(i);
			// 设置custId,contractId
			// CustomerCache.refresh();
			if (CustomerCache.isCustomerBDByCompanyId((Integer) m.get("companyId"))) {
				m.put("custId", "1");
			} else {
				m.put("custId", null);
			}

			if (CustomerCache.isCustomerByCompanyId((Integer) m.get("companyId"))) {
				m.put("contractId", "1");
			} else {
				m.put("contractId", null);
			}
			// 是否有简历附件(R)

			if (this.hasCvAttachment((Integer) m.get("id"))) {
				m.put("attachmentId", 1);

			} else {
				m.put("attachmentId", null);
			}
			// 是否被推荐
			m.put("recomDt", this.getLastCvRecomDt((Integer) m.get("id")));
			if (this.hasCvRecom((Integer) m.get("id"))) {
				m.put("recomId", 1);
			} else {
				m.put("recomId", null);
			}
		}

		return page;
	}

	public void save(Cv entity) throws DataAccessException {
		cvDao.save(entity);
		cvDao.flush();
	}

	public Cv getById(Integer id) {
		Cv cv = (Cv) cvDao.getById(id);
		List lSarary = contactDetailDao.getHibernateTemplate().find("from CvSalary t where t.cvId=?", id);
		CvSalary cvSalary = null;
		if (lSarary != null && lSarary.size() > 0) {
			cvSalary = (CvSalary) lSarary.get(0);
			cv.setCurrentSalary(cvSalary.getCurrentSalary());

		}

		return cv;
	}

	public List<CvResume> findResume(String cv_id) {
		List<CvResume> resumes = new ArrayList<CvResume>();

		List<CvCertificate> certificates = cvEducationDao.findByHql("SELECT c.id,c.beginD,c.papers FROM CvCertificate c where c.CvId = " + cv_id);
		List<CvEducation> educations = cvCertificateDao.findByHql("SELECT e.id,e.beginD,e.endD,e.degree FROM CvEducation e where  e.CvId = " + cv_id);
		List<CvTrainning> trainnings = cvTrainningDao.findByHql("SELECT t.id,t.beginD,t.endD,t.institution FROM CvTrainning t where t.CvId = " + cv_id);
		List<CvWork> works = cvWorkDao.findByHql("SELECT w.id,w.beginD,w.endD,w.degree FROM CvWorkDao w  WHERE w.CvId = " + cv_id);

		if (certificates.size() > 0) {
			for (int i = 0; i < certificates.size(); i++) {
				CvResume cvResume = new CvResume();
				cvResume.setStartTime(certificates.get(i).getBeginDString());
				cvResume.setEndTime(certificates.get(i).getBeginDString());
				cvResume.setCertificate_id(certificates.get(i).getCvId());
				cvResume.setPapers(certificates.get(i).getPapers());
				resumes.add(cvResume);
			}
		}

		if (works.size() > 0) {
			for (int i = 0; i < works.size(); i++) {
				CvResume cvResume = new CvResume();
				cvResume.setWork_id(works.get(i).getCvId());
				cvResume.setStartTime(works.get(i).getBeginDString());
				cvResume.setEndTime(works.get(i).getEndDString());
				cvResume.setPosition(works.get(i).getTitle());
				resumes.add(cvResume);
			}
		}

		if (trainnings.size() > 0) {
			for (int i = 0; i < trainnings.size(); i++) {
				CvResume cvResume = new CvResume();
				cvResume.setWork_id(trainnings.get(i).getCvId());
				cvResume.setStartTime(trainnings.get(i).getBeginDString());
				cvResume.setEndTime(trainnings.get(i).getEndDString());
				cvResume.setInstitution((trainnings.get(i).getInstitution()));
				resumes.add(cvResume);
			}
		}

		if (educations.size() > 0) {
			for (int i = 0; i < educations.size(); i++) {
				CvResume cvResume = new CvResume();
				cvResume.setWork_id(educations.get(i).getCvId());
				cvResume.setStartTime(educations.get(i).getBeginDString());
				cvResume.setEndTime(educations.get(i).getEndDString());
				cvResume.setDegree(educations.get(i).getDegree());
				resumes.add(cvResume);
			}
		}
		return resumes;

	}

	@SuppressWarnings("unchecked")
	public Map<String, Object> getCvHtml(Integer id) {
		Map<String, Object> cvRoot = new HashMap<String, Object>();
		// Cv cv= (Cv)cvDao.getById(id);
		List<CvEducation> eduList = this.getEntityDao().getHibernateTemplate().find(" from CvEducation t where t.cvId=?  and t.isEng='0'  ", id);// cvEducationDao.findAllBy("cvId",
																																					// id);
		List<CvCertificate> certList = this.getEntityDao().getHibernateTemplate().find(" from CvCertificate t where t.cvId=?  and t.isEng='0'  ", id);// cvCertificateDao.findAllBy("cvId",
																																						// id);
		List<CvTrainning> trainList = this.getEntityDao().getHibernateTemplate().find(" from CvTrainning t where t.cvId=?  and t.isEng='0'  ", id);
		List<CvWork> workList = this.getEntityDao().getHibernateTemplate().find(" from CvWork t where t.cvId=?  and t.isEng='0' ", id);
		;// cvWorkDao.findAllBy("cvId", id);
		List<CvSalary> salaryList = salaryDao.findAllBy("cvId", id);
		List skillList = this.getEntityDao().getHibernateTemplate().find(" from CvSkill t where t.cvId=?   ", id);

		Map cvMap = getCvInfoById(id);

		if (cvMap != null) {

			cvMap.put("sex", ConstantDic.getConstantDicCategoryValue(ConstantDic.SEX_TYPE, ObjectUtils.toString(cvMap.get("sex"))));
			cvMap.put("currentAddress", SystemDicCache.getCodeName("LOCATION", ObjectUtils.toString(cvMap.get("currentAddress"))));
			cvMap.put("birthday", DateHelper.toString((Date) cvMap.get("birthday"), DateHelper.DEFAULT_DATE_FORMAT));

			// dataMap.put("cvMap", cvMap);
		}

		/*
		 * if(cv.getMarried()!=null){ String marriedCode =
		 * String.valueOf(cv.getMarried());
		 * cv.setMarried_str(ConstantDic.getConstantDicCategoryValue
		 * (ConstantDic.MARRIED_TYPE, marriedCode)); } if(cv.getSex()!=null){
		 * String sexCode = String.valueOf(cv.getSex());
		 * cv.setSex_str(ConstantDic
		 * .getConstantDicCategoryValue(ConstantDic.SEX_TYPE, sexCode)); }
		 * 
		 * if(cv.getDegree()!=null){ String degreeCode =
		 * String.valueOf(cv.getDegree());
		 * cv.setDegree_str(ConstantDic.getConstantDicCategoryValue("DEGREE",
		 * degreeCode)); }
		 * 
		 * if(cv.getIndustry()!=null){ String industryCode =
		 * String.valueOf(cv.getIndustry());
		 * cv.setIndustry_str(SystemDicCache.getCodeName("INDUSTRY",
		 * industryCode)); }
		 * 
		 * if(cv.getIndustry()!=null){ String industryCode =
		 * String.valueOf(cv.getIndustry());
		 * cv.setIndustry_str(SystemDicCache.getCodeName("INDUSTRY",
		 * industryCode)); }
		 */

		for (int i = 0; i < eduList.size(); i++) {
			// String degreeCode = String.valueOf(cv.getDegree());
			// cv.setDegree_str(ConstantDic.getConstantDicCategoryValue("DEGREE",
			// degreeCode));

			eduList.get(i).setDegree_str(SystemDicCache.getCodeName("DEGREE", ObjectUtils.toString(eduList.get(i).getDegree())));
		}

		// List
		// cvSalary=this.getEntityDao().getHibernateTemplate().find(" from CvSalary t where t.cvId=?  ",
		// contractJobCvRecom.getCvId());
		if (salaryList != null && salaryList.size() > 0) {
			CvSalary oneCvSalary = (CvSalary) salaryList.get(0);
			oneCvSalary.setBonusList(StringHelper.clearHTMLTag(oneCvSalary.getBonusList()));

			oneCvSalary.setExpectSalaryStr(SystemDicCache.getCodeName("SALARY", ObjectUtils.toString(oneCvSalary.getCurrentSalary())));
			oneCvSalary.setCurrentSalaryStr(SystemDicCache.getCodeName("SALARY", ObjectUtils.toString(oneCvSalary.getCurrentSalary())));
			// oneCvSalary.s
			// dataMap.put("cvSalary", oneCvSalary);
		} else {
			// dataMap.put("cvSalary",new CvSalary());
		}

		cvRoot.put("cv", cvMap);
		cvRoot.put("eduList", eduList);
		cvRoot.put("certList", certList);
		cvRoot.put("trainList", trainList);
		cvRoot.put("workList", workList);
		cvRoot.put("salaryList", salaryList);
		cvRoot.put("skillList", skillList);

		return cvRoot;
	}

	public Map getCvInfoById(Integer id) {
		// TODO Auto-generated method stub
		Map m = cvDao.getCvInfoById(id);
		// 转换字典数据
		// industry,function,level,registerLocation,degree,currentSalary,married

		m.put("industry", SystemDicCache.getCodeName(SystemDic.DIC_INDUSTRY, ObjectUtils.toString(m.get("industry"))));
		m.put("function", SystemDicCache.getCodeName(SystemDic.DIC_JOB, ObjectUtils.toString(m.get("function"))));
		m.put("level", SystemDicCache.getCodeName(SystemDic.DIC_JOBLEVEL, ObjectUtils.toString(m.get("level"))));
		m.put("registerLocation", SystemDicCache.getCodeName(SystemDic.DIC_LOCATION, ObjectUtils.toString(m.get("registerLocation"))));
		m.put("degree", SystemDicCache.getCodeName(SystemDic.DIC_DEGREE, ObjectUtils.toString(m.get("degree"))));
		m.put("currentSalary", SystemDicCache.getCodeName(SystemDic.DIC_SALARY, ObjectUtils.toString(m.get("currentSalary"))));

		String married = ObjectUtils.toString(m.get("married"));
		m.put("married", ConstantDic.getConstantDicCategoryValue(ConstantDic.MARRIED_TYPE, married));

		m.put("marriedEn", ConstantDic.getConstantDicCategoryValueEn(ConstantDic.MARRIED_TYPE, married));
		return m;
	}

	public void updateWithContactList(Cv entity, List entitylist) {
		cvDao.update(entity);
		cvDao.flush();

		// 检查是否有薪酬
		List lSarary = contactDetailDao.getHibernateTemplate().find("from CvSalary t where t.cvId=?", entity.getId());
		CvSalary cvSalary = null;
		if (lSarary == null || lSarary.size() == 0) {
			// 新增
			if (ObjectUtils.isNotEmpty(entity.getCurrentSalary())) {
				// cvSalary=(CvSalary)lSarary.get(0);
				cvSalary = new CvSalary();
				cvSalary.setCreator(entity.getModifier());
				cvSalary.setCreateDt(new Date());
				cvSalary.setCvId(entity.getId());
				cvSalary.setCurrency(ConstantDic.MoneyType_RMB);
				cvSalary.setCurrentSalary(entity.getCurrentSalary());
				salaryDao.save(cvSalary);
				salaryDao.flush();
			}

		} else {

			cvSalary = (CvSalary) lSarary.get(0);
			cvSalary.setCurrentSalary(entity.getCurrentSalary());
			salaryDao.update(cvSalary);
			salaryDao.flush();

		}
		// 查询已有的
		List l = contactDetailDao.getHibernateTemplate().find("from CvContactDetail t where t.cvId=?", entity.getId());

		Map allContact = new HashMap();
		CvContactDetail cvContactDetail = null;
		for (int i = 0; l != null && i < l.size(); i++) {
			cvContactDetail = (CvContactDetail) l.get(i);
			allContact.put(cvContactDetail.getId(), cvContactDetail);
		}
		System.out.println(entity.getId() + "entitylist.size(==========" + entitylist.size());
		Set all = new HashSet();
		// all.
		for (int i = 0; i < entitylist.size(); i++) {
			cvContactDetail = (CvContactDetail) entitylist.get(i);
			cvContactDetail.setCvId(entity.getId());

			if (cvContactDetail.getId() != null) {
				if (allContact.containsKey(cvContactDetail.getId()))
					allContact.remove(cvContactDetail.getId());
				contactDetailDao.update(cvContactDetail);
			} else {
				contactDetailDao.save(cvContactDetail);
			}
			contactDetailDao.flush();

		}
		// 删除

		for (Iterator it = allContact.keySet().iterator(); it.hasNext();) {
			contactDetailDao.deleteById((Integer) it.next());
			contactDetailDao.flush();
		}
		contactDetailDao.flush();
		// 更新联系方式
		updateCvContact(entity.getId());
		// 处理,现任公司
		doCompanyCv(entity);
		// 处理客户联系人
		//
		doCompanyContacter(entity);

	}

	@Override
	public void update(Cv entity) throws DataAccessException {
		cvDao.update(entity);
		cvDao.flush();
	}

	@Transactional
	public void saveWithContentList(Cv entity, List entitylist) {
		cvDao.save(entity);
		cvDao.flush();
		// 检查是否有薪酬
		List lSarary = contactDetailDao.getHibernateTemplate().find("from CvSalary t where t.cvId=?", entity.getId());
		CvSalary cvSalary = null;
		if (lSarary == null || lSarary.size() == 0) {
			// 新增
			if (ObjectUtils.isNotEmpty(entity.getCurrentSalary())) {
				// cvSalary=(CvSalary)lSarary.get(0);
				cvSalary = new CvSalary();
				cvSalary.setCreator(entity.getCreator());
				cvSalary.setCreateDt(new Date());
				cvSalary.setCvId(entity.getId());
				cvSalary.setCurrency(ConstantDic.MoneyType_RMB);
				cvSalary.setCurrentSalary(entity.getCurrentSalary());
				salaryDao.save(cvSalary);
				salaryDao.flush();
			}

		} else {

			cvSalary = (CvSalary) lSarary.get(0);
			cvSalary.setCurrentSalary(entity.getCurrentSalary());
			salaryDao.update(cvSalary);
			salaryDao.flush();

		}

		// 查询已有的
		List l = contactDetailDao.getHibernateTemplate().find("from CvContactDetail t where t.cvId=?", entity.getId());

		Map allContact = new HashMap();
		CvContactDetail cvContactDetail = null;
		for (int i = 0; l != null && i < l.size(); i++) {
			cvContactDetail = (CvContactDetail) l.get(i);
			allContact.put(cvContactDetail.getId(), cvContactDetail);
		}

		Set all = new HashSet();
		// all.
		for (int i = 0; i < entitylist.size(); i++) {
			cvContactDetail = (CvContactDetail) entitylist.get(i);
			cvContactDetail.setCvId(entity.getId());

			if (cvContactDetail.getId() != null) {
				if (allContact.containsKey(cvContactDetail.getId()))
					allContact.remove(cvContactDetail.getId());
				contactDetailDao.update(cvContactDetail);
			} else {
				contactDetailDao.save(cvContactDetail);
			}
			contactDetailDao.flush();

		}
		// 删除
		for (Iterator it = allContact.keySet().iterator(); it.hasNext();) {
			contactDetailDao.deleteById((Integer) it.next());
			contactDetailDao.flush();
		}
		// contactDetailDao.flush();
		// log.info("同步联系方式开始。。。");
		// 更新联系方式
		updateCvContact(entity.getId());
		// log.info("同步联系方式结束。。。");

		// 处理,现任公司
		doCompanyCv(entity);

		//
		doCompanyContacter(entity);

		// 联系记录
		doSearchProjectCvCrm(entity);
	}

	public void doCompanyContacter(Cv entity) {
		// 2020 BD联系人
		// 2021 合作决策人
		// 2022 职位联系人
		// 2023 收款联系人
		String roleId = "";
		// CT-BD联系人 CP- 合作决策人JC- 职位联系人 FC-收款联系人 JF-职位/收款联系人
		if ("2020".equals(entity.getCvType()))
			roleId = ConstantDic.CUSTOMER_CONTACTER_TYPE_CONTACTER;
		if ("2021".equals(entity.getCvType()))
			roleId = ConstantDic.CUSTOMER_CONTACTER_TYPE_COOP;
		if ("2022".equals(entity.getCvType()))
			roleId = ConstantDic.CUSTOMER_CONTACTER_TYPE_JOB_CONTACTER;
		if ("2023".equals(entity.getCvType()))
			roleId = ConstantDic.CUSTOMER_CONTACTER_TYPE_FINANCE_CONTACTER;
		// if ("2026".equals(entity.getCvType()))
		// roleId=ConstantDic.CUSTOMER_CONTACTER_TYPE_JOB_FINANCE;

		if (StringHelper.isEmpty(roleId))
			return;

		if (entity.getCompanyId() != null && entity.getCompanyId() != 0) {

			List values0 = new ArrayList();
			values0.add(entity.getCompanyId());
			// 查询是否是客户
			List l0 = cvDao.getJdbcDao().findByQuery("select id from customer b  where b.company_id=?", values0.toArray(), new MapObjectRowMapper());
			Integer custId = null;
			Map m = null;
			if (l0 != null && l0.size() > 0) {
				m = (Map) l0.get(0);
				custId = (Integer) m.get("id");
			}

			if (custId == null)
				return;

			List values = new ArrayList();
			values.add(entity.getCompanyId());
			values.add(entity.getId());
			values.add(roleId);
			List l2 = cvDao.getJdbcDao().findByQuery("select 1 from customer_contacter a,customer b  where b.company_id=? and a.cust_id=b.id and a.cv_id=? and a.role = ? ", values.toArray(), new MapObjectRowMapper());
			if (l2 == null || l2.size() == 0) {

				CustomerContacter customerContacter = new CustomerContacter();
				customerContacter.setCustId(custId);
				customerContacter.setCvId(entity.getId());
				customerContacter.setRole(roleId);
				customerContacter.setCreateDt(new Date());
				if (entity.getModifier() == null)
					customerContacter.setCreator(entity.getCreator());
				else
					customerContacter.setCreator(entity.getModifier());

				customerContacterDao.save(customerContacter);
				customerContacterDao.flush();

			}

			/*
			 * //判断是否选择了 职位/收款联系人 if ("2026".equals(entity.getCvType())) {
			 * List<String> v = new ArrayList<String>(); v.add("JC"); // 职位联系人
			 * v.add("FC"); // 收款联系人 for (String rId : v) { List t = new
			 * ArrayList<String>(); t.add(entity.getCompanyId());
			 * t.add(entity.getId()); t.add(rId); List l1 =
			 * cvDao.getJdbcDao().findByQuery(
			 * "select 1 from customer_contacter a,customer b  where b.company_id=? and a.cust_id=b.id and a.cv_id=? and a.role = ? "
			 * , t.toArray(), new MapObjectRowMapper()); if (l1 == null ||
			 * l1.size() == 0) { CustomerContacter customerContacter = new
			 * CustomerContacter(); customerContacter.setCustId(custId);
			 * customerContacter.setCvId(entity.getId());
			 * customerContacter.setRole(rId); customerContacter.setCreateDt(new
			 * Date()); if (entity.getModifier() == null)
			 * customerContacter.setCreator(entity.getCreator()); else
			 * customerContacter.setCreator(entity.getModifier());
			 * 
			 * customerContacterDao.save(customerContacter);
			 * customerContacterDao.flush();
			 * 
			 * } } }
			 */

		}
	}

	public void doCompanyCv(Cv cv) {
		Cv entity = (Cv) this.cvDao.getById(cv.getId());
		if (entity.getCompanyId() != null && entity.getCompanyId() != 0) {
			List values = new ArrayList();
			values.add(entity.getCompanyId());
			values.add(entity.getId());
			List l1 = cvDao.getJdbcDao().findByQuery("select 1 from company_cv where company_id=? and cv_id=?", values.toArray(), new MapObjectRowMapper());
			if (l1 == null || l1.size() == 0) {
				Integer deptId = null;
				Integer titleId = null;
				// 取缺省部门
				values = new ArrayList();
				values.add(entity.getCompanyId());
				values.add("缺省部门");
				l1 = cvDao.getJdbcDao().findByQuery("select id from company_dept where company_id=? and name=?", values.toArray(), new MapObjectRowMapper());
				Map m = null;
				if (l1 != null && l1.size() > 0) {
					m = (Map) l1.get(0);
					deptId = (Integer) m.get("id");
				}
				// 取缺省岗位
				values = new ArrayList();
				values.add(entity.getCompanyId());
				values.add("缺省岗位");
				l1 = cvDao.getJdbcDao().findByQuery("select id from company_dept_title where company_id=? and name=?", values.toArray(), new MapObjectRowMapper());
				if (l1 != null && l1.size() > 0) {
					m = (Map) l1.get(0);
					titleId = (Integer) m.get("id");
				}
				// 添加到公司树默认部门，默认岗位
				// if (deptId!=null&&titleId!=null){
				CompanyCv companyCv = new CompanyCv();
				companyCv.setCvId(entity.getId());
				companyCv.setCompanyId(entity.getCompanyId());
				companyCv.setTitleId(titleId);
				companyCv.setDeptId(deptId);
				companyCv.setCreateDt(new Date());
				companyCv.setCreator(entity.getCreator());
				cvDao.getHibernateTemplate().save(companyCv);
				cvDao.flush();

				// 设置人才的行业为公司的行业
				Company company = (Company) companyService.getById(companyCv.getCompanyId());
				if (company.getIndustry() != null && ((entity.getIndustry() == null) || entity.getIndustry() != company.getIndustry())) {
					entity.setIndustry(company.getIndustry());
					;
					cvDao.update(entity);
					cvDao.flush();
				}
				if (StringUtils.isEmpty(entity.getCompany())) {
					entity.setCompany(company.getAbbrName());
					cvDao.update(entity);
					cvDao.flush();
				}
				// }
			}
			// 自动并设置cc项目目标公司人选
			searchProjectCvService.addProjectCvByCompanyCv(entity.getCompanyId());
		}
	}

	public Page findSuccessCvPage(CvSuccessQuery query) {
		return cvDao.findSuccessCvPage(query);
	}

	public void saveCompanyTree(SearchProjectCv search) {
		cvDao.saveCompanyTree(search);
	}

	/**
	 * 根据公司名次 获得公司Id
	 */
	public Integer getCompanyId(String companyName) {
		return cvDao.getCompanyId(companyName);
	}

	public boolean isExistSearchProjectCv(Integer cvId, String companyId) {
		return cvDao.isExistSearchProjectCv(cvId, companyId);
	}

	/**
	 * 检查用户是否存在()
	 * 
	 */
	public boolean checkUser(Cv cv, List<CvContactDetail> list) {
		// TODO Auto-generated method stub
		return cvDao.checkUser(cv, list);
	}

	public Page findCustomerContacterCvPage(CvCustomerContacterQuery query) {
		// TODO Auto-generated method stub
		return cvDao.findCustomerContacterCvPage(query);
	}

	/**
	 * 检查简历/人才是否受保护BD客户
	 */
	public boolean isProtectCv(Integer cvId) {

		// TODO Auto-generated method stub
		StringBuffer sql = new StringBuffer();
		List values = new ArrayList();
		// sql.append("select 1 from  customer a,customer_contacter b where a.id=b.cust_id and b.cv_id=?");
		values.add(cvId);
		// List
		// l=cvDao.getJdbcDao().findByQuery(sql.toString(),values.toArray(), new
		// MapObjectRowMapper());
		// if (l!=null&&l.size()>0) return true;
		// 如果人选当前公司为客户公司员工，则受保护
		StringBuffer sqlcv = new StringBuffer();
		sqlcv.append("select 1 from  cv c,customer a,customer_contract b where c.company_id=a.company_id and b.begin_d<=now() and  b.end_d>=now() and a.id=b.cust_id and c.id=?");
		List lcv = cvDao.getJdbcDao().findByQuery(sqlcv.toString(), values.toArray(), new MapObjectRowMapper());
		if (lcv != null && lcv.size() > 0)
			return true;

		return false;
	}

	public void updateCvContact(Integer cvId) {
		StringBuffer sql = new StringBuffer();
		List values = new ArrayList();
		sql.append(" update cv a,(select cv_id,GROUP_CONCAT(if(contact_type='E',nbr,null)) as email,GROUP_CONCAT(if(contact_type='D',nbr,null)) as tel,GROUP_CONCAT(if(contact_type='M',nbr,null)) as mobile from cv_contact_detail where cv_id=? group by cv_id) b ");
		sql.append(" set a.tel=b.tel,a.mobile=b.mobile,a.email=b.email where  a.id=? and a.id=b.cv_id  ");
		values.add(cvId);
		values.add(cvId);
		cvDao.getJdbcDao().getJdbcTemplate().update(sql.toString(), values.toArray());
		cvDao.flush();
	}

	public void updateCvStatus(Integer cvId) {
		// TODO Auto-generated method stub
		StringBuffer sqlcv = new StringBuffer();
		String updatesql = "";
		List values = new ArrayList();
		values.add(cvId);
		sqlcv.append("select 1 from cv a where a.id=? and ( exists (select 1 from cv_education a1 where a.id=a1.cv_id) or  exists (select 1 from cv_certificate a2 where a.id=a2.cv_id) or  exists (select 1 from cv_trainning a3 where a.id=a3.cv_id) or  exists (select 1 from cv_work a4 where a.id=a4.cv_id) or exists (select 1 from cv_attachment a5 where a.id=a5.cv_id))");
		List lcv = cvDao.getJdbcDao().findByQuery(sqlcv.toString(), values.toArray(), new MapObjectRowMapper());
		if (lcv != null && lcv.size() > 0) {
			updatesql = "update cv  set cv_status='F',resume_dt=ifnull(resume_dt,now()) where id=?";
		} else
			updatesql = "update cv  set cv_status='T' where id=?";

		cvDao.getJdbcDao().update(updatesql, values.toArray());
		cvDao.flush();

	}

	public void updateCvStatus(CvAttachment cvAttachment) {
		// TODO Auto-generated method stub
		StringBuffer sqlcv = new StringBuffer();
		String updatesql = "";
		List values = new ArrayList();
		values.add(cvAttachment.getCvId());
		// resumeCreator 简历录入
		Cv cv = this.getById(cvAttachment.getCvId());
		// 只有当 简历创建人 和 创建时间为空时才更新
		if (cv.getResumeCreator() == null && cv.getResumeDt() == null) {
			// 第一个上传附件的人 (只有一个附件)
			sqlcv.append(" select count(a.id) count from cv_attachment a where a.cv_id = ?  ");

		}
		// sqlcv.append(" select count(a.id) count from cv_attachment a where a.cv_id = ?  ");
		int count = cvDao.getJdbcDao().getJdbcTemplate().queryForInt(sqlcv.toString(), cvAttachment.getCvId());
		if (count > 1) {
			updatesql = "update cv  set cv_status='F',resume_dt=ifnull(resume_dt,now()),resume_creator= ?  where id=?";
		} else
			updatesql = "update cv  set cv_status='T' where id=?";
		values.add(cvAttachment.getCreator());

		cvDao.getJdbcDao().update(updatesql, values.toArray());
		cvDao.flush();

	}

	public File genRecomDoc(HttpServletRequest request, OnlineUser onlineUser, Integer cvId) {

		Map dataMap = new HashMap();
		Map cvMap = this.getCvInfoById(cvId);
		if (cvMap != null) {

			cvMap.put("sex", ConstantDic.getConstantDicCategoryValue(ConstantDic.SEX_TYPE, ObjectUtils.toString(cvMap.get("sex"))));
			cvMap.put("married", cvMap.get("married"));
			cvMap.put("birthday", DateHelper.toString((Date) cvMap.get("birthday"), DateHelper.DEFAULT_SHORT_DATE_FORMAT));
			cvMap.put("currentAddress", SystemDicCache.getCodeName("LOCATION", ObjectUtils.toString(cvMap.get("currentAddress"))));

			// 生成图片
			if (cvMap.get("logo") != null) {
				File file = new File(request.getSession().getServletContext().getRealPath((String) cvMap.get("logo")));
				if (file.exists()) {
					String picBase64 = StringHelper.base64Encode(FileHelper.getFileBytes(file));
					cvMap.put("logo", picBase64);
					// FileHelper.getFileBytes(file);
				}
			}
			dataMap.put("cvMap", cvMap);
		}

		// CvCertificate
		// CvEducation
		// CvSkill
		// CvTrainning
		// CvWork
		List cvCertificateList = this.getEntityDao().getHibernateTemplate().find(" from CvCertificate t where t.cvId=?  and t.isEng='0' order by t.beginD desc  ", cvId);
		if (cvCertificateList != null)
			dataMap.put("cvCertificateList", cvCertificateList);
		else {
			cvCertificateList = new ArrayList();
			dataMap.put("cvCertificateList", cvCertificateList);
		}

		List cvEducationList = this.getEntityDao().getHibernateTemplate().find(" from CvEducation t where t.cvId=?  and t.isEng='0' order by t.beginD desc ", cvId);
		if (cvEducationList != null) {
			CvEducation cvEducation = null;
			for (int i = 0; i < cvEducationList.size(); i++) {
				cvEducation = (CvEducation) cvEducationList.get(i);
				cvEducation.setDegree_str(SystemDicCache.getCodeName("DEGREE", ObjectUtils.toString(cvEducation.getDegree())));
			}
			dataMap.put("cvEducationList", cvEducationList);
		} else {
			cvEducationList = new ArrayList();
			dataMap.put("cvEducationList", cvEducationList);
		}

		List cvSkillList = this.getEntityDao().getHibernateTemplate().find(" from CvSkill t where t.cvId=?   ", cvId);

		if (cvSkillList != null)
			dataMap.put("cvSkillList", cvSkillList);
		else {
			cvSkillList = new ArrayList();
			dataMap.put("cvSkillList", cvSkillList);
		}

		List cvTrainningList = this.getEntityDao().getHibernateTemplate().find(" from CvTrainning t where t.cvId=?  and t.isEng='0' order by t.beginD desc ", cvId);
		if (cvTrainningList != null)
			dataMap.put("cvTrainningList", cvTrainningList);
		else {
			cvTrainningList = new ArrayList();
			dataMap.put("cvTrainningList", cvTrainningList);
		}

		// 工作经验
		List cvWorkList = this.getEntityDao().getHibernateTemplate().find(" from CvWork t where t.cvId=?  and t.isEng='0' order by t.beginD desc ", cvId);
		if (cvWorkList != null) {
			List tl = new ArrayList();
			for (int i = 0; i < cvWorkList.size(); i++) {
				CvWork oneorin = (CvWork) cvWorkList.get(i);
				CvWork one = new CvWork();
				tl.add(one);
				BeanUtils.copyProperties(one, oneorin);
				one.setDutyDesc(StringHelper.clearHTMLTag(one.getDutyDesc()));
				one.setProductSize(StringHelper.clearHTMLTag(one.getProductSize()));
				one.setDutySize(StringHelper.clearHTMLTag(one.getDutySize()));
				one.setScore(StringHelper.clearHTMLTag(one.getScore()));
				// one.setCompany(StringHelper.clearHTMLTag(one.getCompany(),true));
				// one.setTitle(StringHelper.clearHTMLTag(one.getTitle(),true));
				one.setLeaveResult(StringHelper.clearHTMLTag(one.getLeaveResult(), true));

			}
			dataMap.put("cvWorkList", tl);
		} else {
			cvWorkList = new ArrayList();
			dataMap.put("cvWorkList", cvWorkList);
		}

		List cvSalary = this.getEntityDao().getHibernateTemplate().find(" from CvSalary t where t.cvId=?  ", cvId);
		if (cvSalary != null && cvSalary.size() > 0) {
			CvSalary one = (CvSalary) cvSalary.get(0);
			CvSalary oneCvSalary = new CvSalary();
			BeanUtils.copyProperties(oneCvSalary, one);
			oneCvSalary.setBonusList(StringHelper.clearHTMLTag(oneCvSalary.getBonusList(), true));
			oneCvSalary.setExpectSalaryStr(SystemDicCache.getCodeName("SALARY", ObjectUtils.toString(oneCvSalary.getExpectSalary())));
			oneCvSalary.setCurrentSalaryStr(SystemDicCache.getCodeName("SALARY", ObjectUtils.toString(oneCvSalary.getCurrentSalary())));

			oneCvSalary.setExpectSalaryEnStr(SystemDicCache.getCodeNameEn("SALARY", ObjectUtils.toString(oneCvSalary.getExpectSalary())));
			oneCvSalary.setCurrentSalaryEnStr(SystemDicCache.getCodeNameEn("SALARY", ObjectUtils.toString(oneCvSalary.getCurrentSalary())));

			dataMap.put("cvSalary", oneCvSalary);
		} else {
			dataMap.put("cvSalary", new CvSalary());
		}

		/*
		 * //发送人信息 SystemUser systemUser=null; if (onlineUser!=null) {
		 * systemUser
		 * =systemUserService.findByUsername(onlineUser.getUsername()); if
		 * (systemUser!=null){ dataMap.put("systemUser", systemUser); }
		 * 
		 * }
		 */
		// 开始生成
		Configuration configuration = new Configuration();
		configuration.setDefaultEncoding("utf-8");
		// configuration.setServletContextForTemplateLoading(request.getSession().getServletContext(),
		// "");
		configuration.setClassForTemplateLoading(this.getClass(), "/resume");
		configuration.setClassicCompatible(true);
		//

		Template t = null;
		try {

			StringBuffer str = FileHelper.read(this.getClass().getResource("/resume/cv.ftl").getPath(), "UTF-8");
			String templateText = str.toString().replaceAll("<!---", "").replaceAll("--->", "");

			StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
			stringTemplateLoader.putTemplate("template", templateText);
			// test.ftl为要装载的模板
			configuration.setTemplateLoader(stringTemplateLoader);
			t = configuration.getTemplate("template");

			// configuration.s
		} catch (IOException e) {
			e.printStackTrace();
		}

		// 输出文档路径及名称
		SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMdd");
		String fileWebPathDir = Environment.UPLOADFILEDIR + "/" + SystemConstant.JOBRECOMDIR + "/" + dateformat.format(new Date()) + "/" + cvId;
		/** 得到文件保存目录的真实路径 **/
		String fileRealPathDir = request.getSession().getServletContext().getRealPath(fileWebPathDir);
		/** 根据真实路径创建目录 **/
		File fileSaveDir = new File(fileRealPathDir);
		// fileSaveDir.i
		if (!fileSaveDir.exists()) {
			fileSaveDir.mkdirs();
		}
		// String fileName="CV_EN_"+contractJobCvRecom.getCvId()+".doc";
		String cvName = (String) cvMap.get("cvName");
		// String fileName= cvName+"_"+jobName+"_"+DateHelper.toString(new
		// Date(), "yyyyMMdd")+"(英).doc";
		String fileName = RandomStringUtil.getString(8) + ".doc";
		File outFile = new File(request.getSession().getServletContext().getRealPath(fileWebPathDir + "/" + fileName));

		Writer out = null;
		try {

			out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"));
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		try {
			// System.out.println(t.toString());

			t.process(dataMap, out);
		} catch (TemplateException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {

			e.printStackTrace();
			return null;
		} finally {
			if (out != null)
				try {
					out.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}

		return outFile;
	}

	public File genRecomDocEn(HttpServletRequest request, OnlineUser onlineUser, Integer cvId) {

		// TODO Auto-generated method stub
		Map dataMap = new HashMap();

		// ContractJob contractJob
		// ContractJobCvRecom contractJobCvRecom=new ContractJobCvRecom();

		/*
		 * if (pContractJobCvRecom==null) return null; ContractJobCvRecom
		 * tempContractJobCvRecom
		 * =(ContractJobCvRecom)contractJobCvRecomDao.getById
		 * (pContractJobCvRecom.getId());
		 * BeanUtils.copyProperties(contractJobCvRecom, tempContractJobCvRecom);
		 */

		// dataMap.put("contractJobCvRecom", contractJobCvRecom);
		// contractJobCvRecom.setRecomResult(StringHelper.clearHTMLTag(contractJobCvRecom.getRecomResult()));
		// contractJobCvRecom.setRecomRisk(StringHelper.clearHTMLTag(contractJobCvRecom.getRecomRisk()));
		// contractJobCvRecom.setSummary(StringHelper.clearHTMLTag(contractJobCvRecom.getSummary()));

		// ContractJob
		// contractJob=(ContractJob)contractJobService.getById(contractJobCvRecom.getJobId());
		Map jobMap = new HashMap();

		/*
		 * if (contractJob!=null) { jobMap.put("name", contractJob.getName());
		 * jobMap.put("workLocation", SystemDicCache.getCodeName("LOCATION",
		 * ObjectUtils.toString(contractJob.getWorkLocation())));
		 * dataMap.put("contractJob", jobMap); }
		 */

		// cv
		Map cvMap = getCvInfoById(cvId);
		if (cvMap != null) {

			cvMap.put("sex", ConstantDic.getConstantDicCategoryValueEn(ConstantDic.SEX_TYPE, ObjectUtils.toString(cvMap.get("sex"))));
			cvMap.put("married", cvMap.get("marriedEn"));
			cvMap.put("birthday", DateHelper.toString((Date) cvMap.get("birthday"), DateHelper.DEFAULT_SHORT_DATE_FORMAT));
			cvMap.put("currentAddress", SystemDicCache.getCodeName("LOCATION", ObjectUtils.toString(cvMap.get("currentAddress"))));

			// 生成图片
			if (cvMap.get("logo") != null) {
				File file = new File(request.getSession().getServletContext().getRealPath((String) cvMap.get("logo")));
				if (file.exists()) {
					String picBase64 = StringHelper.base64Encode(FileHelper.getFileBytes(file));
					cvMap.put("logo", picBase64);
					// FileHelper.getFileBytes(file);
				}
			}
			dataMap.put("cvMap", cvMap);
		}

		// CvCertificate
		// CvEducation
		// CvSkill
		// CvTrainning
		// CvWork
		List cvCertificateList = this.getEntityDao().getHibernateTemplate().find(" from CvCertificate t where t.cvId=?  and t.isEng='1' order by t.beginD desc  ", cvId);
		if (cvCertificateList != null)
			dataMap.put("cvCertificateList", cvCertificateList);
		else {
			cvCertificateList = new ArrayList();
			dataMap.put("cvCertificateList", cvCertificateList);
		}

		List cvEducationList = this.getEntityDao().getHibernateTemplate().find(" from CvEducation t where t.cvId=?  and t.isEng='1' order by t.beginD desc  ", cvId);
		if (cvEducationList != null) {
			CvEducation cvEducation = null;
			for (int i = 0; i < cvEducationList.size(); i++) {
				cvEducation = (CvEducation) cvEducationList.get(i);
				cvEducation.setDegree_str(SystemDicCache.getCodeNameEn("DEGREE", ObjectUtils.toString(cvEducation.getDegree())));
			}
			dataMap.put("cvEducationList", cvEducationList);
		} else {
			cvEducationList = new ArrayList();
			dataMap.put("cvEducationList", cvEducationList);
		}

		List cvSkillList = this.getEntityDao().getHibernateTemplate().find(" from CvSkill t where t.cvId=?   ", cvId);

		if (cvSkillList != null)
			dataMap.put("cvSkillList", cvSkillList);
		else {
			cvSkillList = new ArrayList();
			dataMap.put("cvSkillList", cvSkillList);
		}

		List cvTrainningList = this.getEntityDao().getHibernateTemplate().find(" from CvTrainning t where t.cvId=?  and t.isEng='1' order by t.beginD desc ", cvId);
		if (cvTrainningList != null)
			dataMap.put("cvTrainningList", cvTrainningList);
		else {
			cvTrainningList = new ArrayList();
			dataMap.put("cvTrainningList", cvTrainningList);
		}

		// 工作经验
		List cvWorkList = this.getEntityDao().getHibernateTemplate().find(" from CvWork t where t.cvId=?  and t.isEng='1' order by t.beginD desc ", cvId);
		if (cvWorkList != null) {
			List tl = new ArrayList();
			for (int i = 0; i < cvWorkList.size(); i++) {
				CvWork oneorin = (CvWork) cvWorkList.get(i);
				CvWork one = new CvWork();
				tl.add(one);
				BeanUtils.copyProperties(one, oneorin);
				one.setDutyDesc(StringHelper.clearHTMLTag(one.getDutyDesc()));
				one.setProductSize(StringHelper.clearHTMLTag(one.getProductSize()));
				one.setDutySize(StringHelper.clearHTMLTag(one.getDutySize()));
				one.setScore(StringHelper.clearHTMLTag(one.getScore()));
				// one.setCompany(StringHelper.clearHTMLTag(one.getCompany(),true));
				// one.setTitle(StringHelper.clearHTMLTag(one.getTitle(),true));
				one.setLeaveResult(StringHelper.clearHTMLTag(one.getLeaveResult(), true));

			}
			dataMap.put("cvWorkList", tl);
		} else {
			cvWorkList = new ArrayList();
			dataMap.put("cvWorkList", cvWorkList);
		}

		List cvSalary = this.getEntityDao().getHibernateTemplate().find(" from CvSalary t where t.cvId=?  ", cvId);
		if (cvSalary != null && cvSalary.size() > 0) {
			CvSalary one = (CvSalary) cvSalary.get(0);
			CvSalary oneCvSalary = new CvSalary();
			BeanUtils.copyProperties(oneCvSalary, one);
			oneCvSalary.setBonusList(StringHelper.clearHTMLTag(oneCvSalary.getBonusList(), true));
			oneCvSalary.setExpectSalaryStr(SystemDicCache.getCodeName("SALARY", ObjectUtils.toString(oneCvSalary.getExpectSalary())));
			oneCvSalary.setCurrentSalaryStr(SystemDicCache.getCodeName("SALARY", ObjectUtils.toString(oneCvSalary.getCurrentSalary())));

			oneCvSalary.setExpectSalaryEnStr(SystemDicCache.getCodeNameEn("SALARY", ObjectUtils.toString(oneCvSalary.getExpectSalary())));
			oneCvSalary.setCurrentSalaryEnStr(SystemDicCache.getCodeNameEn("SALARY", ObjectUtils.toString(oneCvSalary.getCurrentSalary())));

			dataMap.put("cvSalary", oneCvSalary);
		} else {
			dataMap.put("cvSalary", new CvSalary());
		}

		// 发送人信息
		/*
		 * SystemUser systemUser=null; if (onlineUser!=null) {
		 * systemUser=systemUserService
		 * .findByUsername(onlineUser.getUsername()); if (systemUser!=null){
		 * dataMap.put("systemUser", systemUser); }
		 * 
		 * }
		 */

		// 开始生成
		Configuration configuration = new Configuration();
		configuration.setDefaultEncoding("utf-8");
		// configuration.setServletContextForTemplateLoading(request.getSession().getServletContext(),
		// "");
		configuration.setClassForTemplateLoading(this.getClass(), "/resume");
		configuration.setClassicCompatible(true);
		//

		Template t = null;
		try {

			StringBuffer str = FileHelper.read(this.getClass().getResource("/resume/encv.ftl").getPath(), "UTF-8");
			String templateText = str.toString().replaceAll("<!---", "").replaceAll("--->", "");

			StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
			stringTemplateLoader.putTemplate("template", templateText);
			// test.ftl为要装载的模板
			configuration.setTemplateLoader(stringTemplateLoader);
			t = configuration.getTemplate("template");

			// configuration.s
		} catch (IOException e) {
			e.printStackTrace();
		}

		// 输出文档路径及名称
		SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMdd");
		String fileWebPathDir = Environment.UPLOADFILEDIR + "/" + SystemConstant.JOBRECOMDIR + "/" + dateformat.format(new Date()) + "/" + cvId;
		/** 得到文件保存目录的真实路径 **/
		String fileRealPathDir = request.getSession().getServletContext().getRealPath(fileWebPathDir);
		/** 根据真实路径创建目录 **/
		File fileSaveDir = new File(fileRealPathDir);
		// fileSaveDir.i
		if (!fileSaveDir.exists()) {
			fileSaveDir.mkdirs();
		}
		// String fileName="CV_EN_"+contractJobCvRecom.getCvId()+".doc";
		String cvName = (String) cvMap.get("cvName");
		// String jobName=contractJob.getName();
		// String fileName= cvName+"_"+jobName+"_"+DateHelper.toString(new
		// Date(), "yyyyMMdd")+"(英).doc";
		String fileName = RandomStringUtil.getString(8) + "_EN.doc";
		// pContractJobCvRecom.setUploadDocEn(fileWebPathDir+"/"+ fileName);
		File outFile = new File(request.getSession().getServletContext().getRealPath(fileWebPathDir + "/" + fileName));

		Writer out = null;
		try {

			out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"));
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		try {

			t.process(dataMap, out);
		} catch (TemplateException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {

			e.printStackTrace();
			return null;
		} finally {
			if (out != null)
				try {
					out.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}

		return outFile;
	}

	public void cvApplyJob(Integer jobId, Cv cv, CvSalary cvSalary, String cvMobile, String cvEmail) {
		// TODO Auto-generated method stub
		//
		// 查询职位
		List values = new ArrayList();
		values.add(jobId);

		List l = cvDao.getJdbcDao().findByQuery("select a.id,b.email,b.email_passwd from  contract_job a left join system_user b on a.creator=b.account where a.id=? ", values.toArray(), new MapObjectRowMapper());
		String email = "";
		String mwpasswod = null;
		Map m = null;
		if (l != null && l.size() > 0) {
			m = (Map) l.get(0);
			email = (String) m.get("email");
			mwpasswod = (String) m.get("b.email_passwd");
		}
		values = new ArrayList();
		values.add(cv.getCvName());
		values.add(cvMobile);
		values.add(cvEmail);
		l = cvDao.getJdbcDao().findByQuery("select distinct a.id from  cv a left join cv_contact_detail b on a.id=b.cv_id where a.cv_name=? and (if(b.contact_type='" + ConstantDic.ContactType_EMAIL + "',b.nbr,null)=? or if(b.contact_type='" + ConstantDic.ContactType_MOBILE + "',b.nbr,null)=? ) ", values.toArray(), new MapObjectRowMapper());

		Integer cvId = null;
		if (l != null && l.size() > 0) {
			m = (Map) l.get(0);
			cvId = (Integer) m.get("id");
		}
		// 如果为空则保存简历
		if (cvId == null) {
			cvDao.save(cv);
			cvId = cv.getId();
			cvDao.flush();
		} else
			cv.setId(cvId);

		if (cvSalary.getCurrentSalary() != null && cvSalary.getCurrentSalary().intValue() != 0) {
			cvSalary.setCvId(cvId);
			cvSalary.setCurrency(ConstantDic.MoneyType_RMB);
			cvSalary.setCreator("system");
			cvSalary.setCreateDt(new Date());
			cvDao.save(cvSalary);
			cvDao.flush();
		}
		CvContactDetail cvContactDetail = null;
		if (!StringHelper.isEmpty(cvMobile)) {
			cvContactDetail = new CvContactDetail();
			cvContactDetail.setCreator("system");
			cvContactDetail.setContactType(ConstantDic.ContactType_MOBILE);
			cvContactDetail.setNbr(cvMobile);
			cvContactDetail.setCvId(cvId);
			// System.out.println("--------------------"+cvContactDetail.getCvId());
			cvContactDetail.setCreateDt(new Date());
			cvDao.save(cvContactDetail);
			cvDao.flush();
		}
		if (!StringHelper.isEmpty(cvEmail)) {
			cvContactDetail = new CvContactDetail();
			cvContactDetail.setCreator("system");
			cvContactDetail.setCvId(cvId);
			// System.out.println("-------------------2-"+cvContactDetail.getCvId());
			cvContactDetail.setContactType(ConstantDic.ContactType_EMAIL);
			cvContactDetail.setNbr(cvEmail);
			cvContactDetail.setCreateDt(new Date());
			cvDao.save(cvContactDetail);
			cvDao.flush();
		}

		// 保存人选关系
		StringBuffer sb = new StringBuffer();
		sb.append(" insert into search_project_cv(project_id,cv_id,creator,create_dt) ");
		sb.append(" select a.project_id,").append(cvId).append(",'system',now() from contract_job_search_project a ");
		sb.append(" where a.job_id=? and not exists(select 1 from search_project_cv b where a.project_id=b.project_id and b.cv_id=?) ");
		values = new ArrayList();
		values.add(jobId);
		values.add(cvId);
		cvDao.getJdbcDao().getJdbcTemplate().update(sb.toString(), values.toArray());
		cvDao.flush();
		// 发送邮件
		// 取职位的名称
		ContractJob contractJob = (ContractJob) contractJobService.getById(jobId);

		SendMailInfo sendMailInfo = new SendMailInfo();

		sendMailInfo.setMailServerAddress(Environment.MAIL_SERVER);
		sendMailInfo.setAuth(true);
		try {
			if (!StringHelper.isEmpty(mwpasswod))
				mwpasswod = new String(DESHelper.desDecode(DESHelper.hex2byte(mwpasswod), Environment.SECURE_KEY));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Map mv = new HashMap();
		mv.put("cvName", cv.getCvName());
		if (contractJob != null)
			mv.put("jobName", contractJob.getName());
		mv.put("sex", ConstantDic.getConstantDicCategoryValue(ConstantDic.SEX_TYPE, cv.getSex()));
		mv.put("company", cv.getCompany());
		mv.put("position", cv.getPosition());
		mv.put("mobile", cvMobile);
		mv.put("email", cvEmail);

		OaEmailSend oaEmailSend = oaEmailSendService.getJAEmailByMap(mv);
		sendMailInfo.setTitle(oaEmailSend.getSubject());
		sendMailInfo.setContent(oaEmailSend.getContent());

		if (contractJob != null && contractJob.getCustId() != null && contractJob.getCustId().intValue() == 1001) {
			// tb的
			sendMailInfo.setPassword(Environment.MAIL_JOB_SENDER_PASSWORD);
			sendMailInfo.setSenderAddress(Environment.MAIL_JOB_SENDER);
		} else {
			sendMailInfo.setPassword(Environment.MAIL_RECRUIT_SENDER_PASSWORD);
			sendMailInfo.setSenderAddress(Environment.MAIL_RECRUIT_SENDER);
		}
		sendMailInfo.setToAddress(email);
		if (!StringHelper.isEmpty(email)) {
			try {
				if (SendMailUtil.sendNoticeMail(sendMailInfo)) {

				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}

	}

	public void removeById(Integer id) {
		// 改为逻辑删除
		Cv cv = (Cv) cvDao.getById(id);
		cv.setIsDelete(Cv.DELETE_FLAG);
		cv.setDeleteDt(new Date());
		cvDao.update(cv);
		cvDao.flush();
		// 改为逻辑删除
		// List list

	}

	public boolean checkContact(Cv cv, List<CvContactDetail> contact_list) {
		// TODO Auto-generated method stub
		for (CvContactDetail cvContact : contact_list) {

			/*
			 * if(cvContact.getContactType().equals(ConstantDic.ContactType_TEL))
			 * {//电话
			 * 
			 * String nbrExt1s = cvContact.getNbrExt1(); //区号 String nbrs =
			 * cvContact.getNbr(); //电话号码 String nbrExt2s=
			 * cvContact.getNbrExt2(); //分机号
			 * 
			 * List values = new ArrayList(); values.add(nbrExt1s);
			 * values.add(nbrs); values.add(nbrExt2s);
			 * 
			 * List l=cvDao.getJdbcDao().findByQuery(
			 * "select 1 from  cv_contact_detail a where a.contact_type='"
			 * +ConstantDic
			 * .ContactType_TEL+"' and a.nbr_ext1=? and a.nbr=? a.nbr_ext2=? ",
			 * values.toArray(), new MapObjectRowMapper());
			 * if(l!=null&&l.size()>0) return true; //if (oldNbr.equals(newNbr))
			 * return true; // if(nbrExt1.equals(nbrExt1) && nbr.equals(nbrs) &&
			 * nbrExt2.equals(nbrExt2s)){ // return true; // } }else
			 */
			if (cvContact.getContactType().equals(ConstantDic.ContactType_EMAIL)) {// Email

				String email2 = cvContact.getNbr();
				List values = new ArrayList();
				values.add(email2);

				List l = cvDao.getJdbcDao().findByQuery("select 1 from  cv_contact_detail a where a.contact_type='" + ConstantDic.ContactType_EMAIL + "' and  a.is_delete = 0 and  a.nbr=?  ", values.toArray(), new MapObjectRowMapper());
				if (l != null && l.size() > 0)
					return true;
			} else if (cvContact.getContactType().equals(ConstantDic.ContactType_MOBILE)) {// 手机

				String mobile = cvContact.getNbr();
				List values = new ArrayList();
				values.add(mobile);

				List l = cvDao.getJdbcDao().findByQuery("select 1 from  cv_contact_detail a where a.contact_type='" + ConstantDic.ContactType_MOBILE + "' and  a.is_delete = 0 and a.nbr=?  ", values.toArray(), new MapObjectRowMapper());
				if (l != null && l.size() > 0)
					return true;
			}
		}
		return false;
	}

	@Override
	public Page findCvProjectPage(CvQuery query) {
		// TODO Auto-generated method stub
		return cvDao.findCvProjectPage(query);
	}

	@Override
	public void importCvFromExcel(String fileName) {
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
		// 产生报表所用数据
		List<HashMap<String, String>> datas = new ArrayList<HashMap<String, String>>();

		StringBuffer info = new StringBuffer();
		// 公司中文名 公司英文名 公司简称 公司性质 二级行业 机构类型 电话总机 网站 城市 人员规模 公司介绍-内部使用 传真 地址 邮编
		// 公司产品 行业排名 注册资本 资本描述 公司背景 公司文化 公司介绍-外部使用
		// Map paramsMap = new HashMap();
		// 公司中文名 公司英文名 公司简称 公司性质 二级行业 机构类型 电话总机 网站 城市 人员规模 公司介绍-内部使用 传真 地址 邮编
		// 公司产品 行业排名 注 册资本 资本描述 公司背景 公司文化 公司介绍-外部使用
		/**
		 * id cv_name cv_name_en name_informer name_dt sex birthday mobile tel
		 * im email company dept title industry function level married
		 * register_location address post_code degree work_year home_back
		 * interest_en interest expect_location resume_informer resume_dt
		 * cv_type cv_status cv_from base_creator creator create_dt modifier
		 * modified_dt home_back_en logo oldcompany current_address company_id
		 * resume_creator oldcompany_id cv_tag cv_fl_level nationality position
		 * integrity is_delete delete_dt cv_text
		 */
		// 中文名 英文名 性别 手机 电话（分机） 电子邮件 人选类别 人选标签 现任公司 现职位名称 职级 二级行业 二级职能 所在城市
		// 期望工作地 当前所在地 国籍 家庭地址 邮政编码 出生日期 学历 婚姻状况 外语能力 年薪范围 开始工作年份
		String[] params = { "cvName", "cvNameEn", "sex", "mobile", "tel", "email", "cvType", "cvTag", "company", "position", "level", "industry", "function", "registerLocation", "expectLocation", "currentAddress", "contactContext", "nationality", "address", "postCode", "birthday", "degree", "married", "cvFlLevel", "currentSalary", "workYear" };

		//
		try {
			InputStream inputStream = new FileInputStream(fileName);
			// 创建对Excel工作簿文件的引用
			HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
			// 创建对工作表的引用。
			HSSFSheet sheet = workbook.getSheetAt(0);
			// 遍历所有单元格，读取单元格
			int it = 1;
			for (int i = 1; i <= sheet.getLastRowNum(); i++) {
				HSSFRow row = sheet.getRow(i);
				if (row != null) {
					Cv cv = new Cv();
					cv.setCreateDt(new Date());
					cv.setCreator("cherry.chen");
					cv.setNameInformer("cherry.chen");
					for (int j = 0; j < row.getLastCellNum(); j++) {
						HSSFCell cell = row.getCell(j); // 获取每个单元格对象
						if (cell != null) {
							// 通过 row.getCell(j).toString() 获取单元格内容，
							if (j < params.length) {
								if (BeanUtils.isExistsProperty(Cv.class, params[j])) {
									if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) { // 单元格内容为数字
										DecimalFormat df = new DecimalFormat("#");
										BeanUtils.setProperty(cv, params[j], df.format(cell.getNumericCellValue()));
									} else if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
										String value = cell.getStringCellValue();
										if (StringUtils.isNotEmpty(value)) {
											BeanUtils.setProperty(cv, params[j], value.trim());
										}

									}

								}
							}

						}
					}
					if (StringUtils.isEmpty(cv.getCvName())) {
						cv.setCvName(cv.getCvNameEn());
					}

					// 检查人选是重复
					List<Map> cvList = this.cvDao.findCvList(cv);

					if (cvList != null && cvList.size() > 0) {
						StringBuffer ids = new StringBuffer();
						for (Map map : cvList) {
							ids.append(map.get("cv_id")).append(",");
						}
						HashMap<String, String> mp = new HashMap<String, String>();
						mp.put("id", "");
						mp.put("cvName", cv.getCvName());
						mp.put("ids", ids.substring(0, ids.length() - 1));
						datas.add(mp);
						log.info("第" + i + "个人选:" + cv.getCvName() + "已经存在!");
					} else {
						if (StringUtils.isNotEmpty(cv.getCvName())) {
							this.saveWithContentList(cv, this.addContacts(cv));
							HashMap<String, String> mp = new HashMap<String, String>();
							mp.put("id", cv.getId().toString());
							mp.put("cvName", cv.getCvName());
							mp.put("ids", "");
							datas.add(mp);
							log.info("第" + i + "个人选:" + cv.getCvName() + "导入成功!");
							info.append("编号:" + cv.getId() + "; 姓名:" + cv.getCvName() + "---->Success ! \r\n ");
						}

					}
				}

				/*
				 * if(i>100){ break; }
				 */

			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		log.info("========开始生成人选导入报告======");
		try {
			Map map = new HashMap<String, String>();
			map.put("id", "编号");
			map.put("cvName", "姓名");
			map.put("ids", "人选重复ID");
			String fileN = "C:\\人选导入报告" + sf.format(new Date()) + ".xls";
			FileOutputStream file = new FileOutputStream(fileN);
			HSSFWorkbook wb = ExcelHelper.createExcelWorkbook("人选导入报告", datas, map);
			wb.write(file);
			file.flush();
			file.close();
			log.info("========生成人选导入报告结束======");

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			/*
			 * if (bufferedWriter != null) { try { bufferedWriter.close(); }
			 * catch (Exception e2) { e2.printStackTrace(); } }
			 */
		}

		// cvDao.importCvFromExcel(fileName);
	}

	/**
	 * 根据人选联系信息 生成 联系方式 List
	 * 
	 * @param cv
	 * @return li
	 */
	public List addContacts(Cv cv) {
		List list = new ArrayList();
		if (StringUtils.isNotEmpty(cv.getMobile())) {
			String[] m = cv.getMobile().split(",");
			for (String phone : m) {
				CvContactDetail contactDetail = new CvContactDetail();
				contactDetail.setContactType(ConstantDic.ContactType_MOBILE);
				contactDetail.setNbr(phone.trim());
				contactDetail.setCreateDt(new Date());
				list.add(contactDetail);
			}

		}
		if (StringUtils.isNotEmpty(cv.getEmail())) {
			CvContactDetail contactDetail = new CvContactDetail();
			contactDetail.setContactType(ConstantDic.ContactType_EMAIL);
			contactDetail.setNbr(cv.getEmail());
			contactDetail.setCreateDt(new Date());
			list.add(contactDetail);
		}
		if (StringUtils.isNotEmpty(cv.getTel())) {
			String[] c = cv.getTel().split(","); // 判断是否有多个电话号码
			for (String t : c) {
				// 处理区号 分机号 标准格式 (020-xxxxxxxx-xxx)
				String[] tel = t.split("-");
				if (tel.length == 1) {
					// 只有电话号码,没有 区号 分机号
					CvContactDetail contactDetail = new CvContactDetail();
					contactDetail.setContactType(ConstantDic.ContactType_TEL);
					contactDetail.setNbr(tel[0].trim());
					contactDetail.setCreateDt(new Date());
					list.add(contactDetail);

				} else if (tel.length == 2) { // 有区号 或者 分机号
					CvContactDetail contactDetail = new CvContactDetail();
					contactDetail.setContactType(ConstantDic.ContactType_TEL);
					// contactDetail.setNbr(tel[0]);
					contactDetail.setCreateDt(new Date());
					list.add(contactDetail);
					if (tel[0].length() <= 4) { // 区号一般为四位
						// 为区号
						contactDetail.setNbrExt1(tel[0].trim());// setNbr1();
						contactDetail.setNbr(tel[1].trim());
					} else {
						// 电话号码
						contactDetail.setNbr(tel[0].trim());
						contactDetail.setNbrExt2(tel[1].trim());
					}
				} else if (tel.length == 3) {
					CvContactDetail contactDetail = new CvContactDetail();
					contactDetail.setContactType(ConstantDic.ContactType_TEL);
					contactDetail.setNbrExt1(tel[0].trim());
					contactDetail.setNbr(tel[1].trim());
					contactDetail.setNbrExt1(tel[2].trim()); // 分机号
					contactDetail.setCreateDt(new Date());
					list.add(contactDetail);
				}

			}

		}
		return list;
	}

	/**
	 * 是否有简历
	 * 
	 * @param cvId
	 *            人选
	 * @return 有无简历
	 */
	public boolean hasCvAttachment(Integer cvId) {
		StringBuffer sql = new StringBuffer();
		List values = new ArrayList();
		if (cvId != null && cvId > 0) {
			sql.append(" select 1 from cv_attachment a  where 1=1 and a.type='R' and a.cv_id = ? ");
			values.add(cvId);
			List list = cvDao.getJdbcDao().findByQuery(sql.toString(), values.toArray(), new MapObjectRowMapper());
			if (list != null && list.size() > 0) {
				// 有简历附件
				return true;
			}
		}
		return false;
	}

	/**
	 * 是否被推荐过
	 * 
	 * @param cvId
	 * @return
	 */
	public boolean hasCvRecom(Integer cvId) {
		StringBuffer sql = new StringBuffer();
		List values = new ArrayList();
		if (cvId != null && cvId > 0) {
			sql.append(" select 1 from contract_job_cv_recom a  where 1=1  and a.cv_id = ? ");
			values.add(cvId);
			List list = cvDao.getJdbcDao().findByQuery(sql.toString(), values.toArray(), new MapObjectRowMapper());
			if (list != null && list.size() > 0) {
				// 已经推荐
				return true;
			}
		}
		return false;
	}

	/**
	 * 是否被推荐过
	 * 
	 * @param cvId
	 * @return
	 */
	public Date getLastCvRecomDt(Integer cvId) {
		// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ");
		StringBuffer sql = new StringBuffer();
		List values = new ArrayList();
		if (cvId != null && cvId > 0) {
			sql.append(" select max(a.create_dt) as  recomDt from contract_job_cv_recom a  where 1=1  and a.cv_id = ? ");
			values.add(cvId);
			List list = cvDao.getJdbcDao().findByQuery(sql.toString(), values.toArray(), new MapObjectRowMapper());
			if (list != null && list.size() > 0) {
				// 已经推荐
				Map map = (Map) list.get(0);
				return (Date) map.get("recomDt");
			}
		}
		return null;
	}

	/**
	 * 新增联系记录
	 * 
	 * @param entity
	 */
	public void doSearchProjectCvCrm(Cv cv) {
		if (StringUtils.isNotEmpty(cv.getContactContext())) {
			String[] context = cv.getContactContext().split("#");
			for (String text : context) {
				SearchProjectCvCrm crm = new SearchProjectCvCrm();
				crm.setCreator(cv.getCreator());
				crm.setCreateDt(new Date());
				crm.setCrmDt(new Date());
				crm.setCvId(cv.getId());
				crm.setCrmType(ConstantDic.ContactMethod_C); // 联系类型 默认为 C-电话/视频
				crm.setComment(text);
				crm.setProjectId(cv.getProjectId());
				this.crmService.save(crm);
			}
		}

	}

	@Override
	/**
	 * offer和账单
	 */
	public boolean hasAccountPn(Integer cvId) {

		return cvDao.hasAccountPn(cvId);
	}

	@Override
	public Page findCvDelPage(CvQuery cvQuery) {
		// TODO Auto-generated method stub
		return cvDao.findCvDelPage(cvQuery);
	}

	@Override
	public Page findCvMergePage(CvQuery cvQuery) {
		// TODO Auto-generated method stub
		return cvDao.findCvMergePage(cvQuery);
	}

	@Override
	public void cvMerger(String id, String cvIds) {
		cvDao.cvMerger(id, cvIds);

	}

	@Override
	public Page findSameOfDelCvPage(CvQuery cvQuery) {
		// TODO Auto-generated method stub
		return cvDao.findSameOfDelCvPage(cvQuery);
	}

	@Override
	public void recoverCv(String ids) {
		cvDao.recoverCv(ids);

	}

}
